/* eslint-disable jsx-a11y/anchor-is-valid */
import React from 'react';

import { Table, Badge, Switch, Typography, Popconfirm, Input, Form, Space, message, Modal, Alert, Button, InputNumber, DatePicker ,Col, Row} from 'antd';
import { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { useDeletuserPropsHalfHourCalMutation, useGetuserPropsHalfHourCalQuery, usePostaddduserPropsHalfHourCalMutation, usePosthalfhourcalexcuteMutation, usePutedituserPropsHalfHourCalMutation } from '../../store/request/dataworksrequests/userpropshalfhourcalrequest';
//import { useLocation,useNavigate } from 'react-router-dom';

// const { confirm } = Modal;

const UserHalfHourCalProp = () => {
  // const isEmptyObject = (obj) => {
  //   for (var key in obj) {
  //     if (obj.hasOwnProperty(key)) {
  //       return false;
  //     }
  //   }
  //   return true;
  // };
  const loginstate = useSelector(state => state.loginpara);//loginpara={isLogined,role:{key,loginname,authoritykey,avatarpath}}
  const [paraisselected, setparaisselected] = useState(false);//用于判断是否有选中行以此来空值执行按钮的生效

  const [loading, setloading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);//设置表格里的是否选中异常值



  const [selectpara, setselectpara] = useState("");//设置选中行的异常值并存储进state
  const [selectdate, setselectdate] = useState("");//设置添加的日期并存储进state
  const [dateselected, setdateselected] = useState(false);//用于判断是否选择了日期执行按钮的生效
  const [selectnewrow, setselectnewrow] = useState({});//设置选中行的值和添加的日期并存储进state


  const [resultString, setResult] = useState("异常值修正执行成功");//存储请求处理执行的结果
  const [excutesuccess, setexcutesuccess] = useState(-1);//设置是否执行成功，用于显示提示成功或失败信息


  //选中时选取异常值
  const handleSelectChange = (selectedRowKeys, selectedRows) => {

    setSelectedRowKeys(selectedRowKeys);
    setparaisselected(true); // 执行按钮可以使用
    setselectpara(selectedRows[0]); // 把选中行的异常值存储到state中
    //判断是否选择了日期
    if (dateselected) {
      const newrow = { ...selectedRows[0], startdate: selectdate[0], enddate: selectdate[1] };
      setselectnewrow(newrow);
    }
    // if (!isEmptyObject(selectnewrow)) {
    //   const updatedSelectnewrow = { ...selectnewrow };
    //   if (updatedSelectnewrow.hasOwnProperty('loginname')) {
    //     updatedSelectnewrow.loginname = selectedRows[0].loginname;
    //   }
    //   if (updatedSelectnewrow.hasOwnProperty('savepath')) {
    //     updatedSelectnewrow.savepath = selectedRows[0].savepath;
    //   }
    //   if (updatedSelectnewrow.hasOwnProperty('chantitle_spd')) {
    //     updatedSelectnewrow.chantitle_spd = selectedRows[0].chantitle_spd;
    //   }
    //   if (updatedSelectnewrow.hasOwnProperty('vehicle')) {
    //     updatedSelectnewrow.vehicle = selectedRows[0].vehicle;
    //   }
    //   if (updatedSelectnewrow.hasOwnProperty('project')) {
    //     updatedSelectnewrow.project = selectedRows[0].project;
    //   }
    //   if (updatedSelectnewrow.hasOwnProperty('remarks')) {
    //     updatedSelectnewrow.remarks = selectedRows[0].remarks;
    //   }

    //   if (updatedSelectnewrow.hasOwnProperty('chantitle_throttle')) {
    //     updatedSelectnewrow.chantitle_throttle = selectedRows[0].chantitle_throttle;
    //   }
    //   if (updatedSelectnewrow.hasOwnProperty('chantitle_brake')) {
    //     updatedSelectnewrow.chantitle_brake = selectedRows[0].chantitle_brake;
    //   }
    //   if (updatedSelectnewrow.hasOwnProperty('brakezerostandard')) {
    //     updatedSelectnewrow.brakezerostandard = selectedRows[0].brakezerostandard;
    //   }
    //   if (updatedSelectnewrow.hasOwnProperty('chantitle_steering')) {
    //     updatedSelectnewrow.chantitle_steering = selectedRows[0].chantitle_steering;
    //   }
    //   if (updatedSelectnewrow.hasOwnProperty('chantitle_engspd')) {
    //     updatedSelectnewrow.chantitle_engspd = selectedRows[0].chantitle_engspd;
    //   }
    //   if (updatedSelectnewrow.hasOwnProperty('importspd')) {
    //     updatedSelectnewrow.importspd = selectedRows[0].importspd;
    //   }
    //   if (updatedSelectnewrow.hasOwnProperty('importgps')) {
    //     updatedSelectnewrow.importgps = selectedRows[0].importgps;
    //   }
    //   if (updatedSelectnewrow.hasOwnProperty('importstatistic')) {
    //     updatedSelectnewrow.importstatistic = selectedRows[0].importstatistic;
    //   }
    //   if (updatedSelectnewrow.hasOwnProperty('importsteering')) {
    //     updatedSelectnewrow.importsteering = selectedRows[0].importsteering;
    //   }
    //   if (updatedSelectnewrow.hasOwnProperty('importengrpm')) {
    //     updatedSelectnewrow.importengrpm = selectedRows[0].importengrpm;
    //   }
    //   if (updatedSelectnewrow.hasOwnProperty('importspdfromto')) {
    //     updatedSelectnewrow.importspdfromto = selectedRows[0].importspdfromto;
    //   }
    //   setselectnewrow(updatedSelectnewrow);
    //   //console.log(updatedSelectnewrow);
    // }
  };
  const rowSelection = {
    type: "radio",
    selectedRowKeys,
    onChange: handleSelectChange,
  };

  const [messageApi, contextHolder] = message.useMessage();
  const [tableParams, setTableParams] = useState({
    pagination: {
      current: 1,
      pageSize: 10,
    },
  });
  const getRandomuserParams = (params) => ({
    pagesize: params.pagination?.pageSize,
    page: params.pagination?.current,
    loginname: loginstate.role.loginname
    //...params,
  });
  const [editingKey, setEditingKey] = useState(''); // 初始化正在编辑的 key 的 state
  //用于是否打开添加modal的表单页面
  const [open, setOpen] = useState(false);

  // const [badgestatus, setbadgestatus] = useState([]);

  //tableParams发生变化就会执行发送请求和参数
  const result = useGetuserPropsHalfHourCalQuery(getRandomuserParams(tableParams));
  const [excutetrigger] = usePosthalfhourcalexcuteMutation();
  const [edittrigger] = usePutedituserPropsHalfHourCalMutation();
  const [deltrigger] = useDeletuserPropsHalfHourCalMutation();
  const [addtrigger] = usePostaddduserPropsHalfHourCalMutation();
  // const [delquartztrigger] = useDeletquartzremoveMutation();

  const [form] = Form.useForm(); // 从 Form.useForm() 中解构 form
  const isEditing = (record) => record.key === editingKey; // 定义 isEditing 函数以检查记录是否正在被编辑

  //dateString:['2024-02-01', '2024-02-08']
  const dateselect = (date, dateString) => {
    if (dateString.length === 2) {
      setdateselected(true);//标识选择了日期
      setselectdate(dateString);
      const newrow = { ...selectpara, startdate: dateString[0], enddate: dateString[1] };
      setselectnewrow(newrow);
      //console.log(newrow);
    }
    else {
      setdateselected(false);//标识没选择日期
    }

  };

  //执行半小时导入
  const dataimportexcute = async () => {
    setloading(true);
    const r = await excutetrigger(selectnewrow);
    if (r.error.originalStatus === 200) {
      //console.log("成功")
      messagesucess("success");
      const formattedResult = r.error.data.replace(/\n/g, '<br>');
      setResult(formattedResult);
      setexcutesuccess(1);

    } else {
      messageerror("error");
      setexcutesuccess(0);
    }
    setloading(false);

  };

  // 定义 edit 函数以将 editingKey state 设置为记录的 key
  //表单更新异常值只能用setFieldsValue方法，不能用setstate方法，这样就能获取原始值
  const edit = (record) => {

    form.setFieldsValue({

      key: record.key,
      loginname: record.loginname,
      savepath: record.savepath,
      inputpath: record.inputpath,
      chantitle_spd: record.chantitle_spd,
      chantitle_throttle: record.chantitle_throttle,
      chantitle_brake: record.chantitle_brake,
      brakezerostandard: record.brakezerostandard,
      chantitle_steering: record.chantitle_steering,
      chantitle_engspd: record.chantitle_engspd,
      chantitle_accybody: record.chantitle_accybody,
      importgps: record.importgps,
      importspd: record.importspd,
      importstatistic: record.importstatistic,
      importsteering: record.importsteering,
      importengrpm: record.importengrpm,
      importspdfromto: record.importspdfromto,
      vehicle: record.vehicle,
      project: record.project,
      remarks: record.remarks,
      ecnumber: record.ecnumber
      //...record,  //一展开record，就会报错date.locale is not a function，但是之前arriveddate已经赋值为空字符串，所以除了arriveddate为空外，其余属性按照record展开
    });

    setEditingKey(record.key);
  };

  const messageerror = (editordel) => {
    //message.success('This is a success message');
    messageApi.open({
      type: 'error',
      content: editordel,
    });
    //console.log("消息框");
  };
  const messagesucess = (editordel) => {
    messageApi.open({
      type: 'success',
      content: editordel,
    });
  };
  //添加异常值的表单页面
  const CollectionCreateForm = ({ open, onCreate, onCancel }) => {
    const [form] = Form.useForm();
    return (
      <Modal
        open={open}
        title="添加半小时计算参数"
        maskClosable={false} 
        okText="添加"
        cancelText="取消"
        onCancel={onCancel}
        onOk={() => {
          form
            .validateFields()
            .then((values) => {
              //form.resetFields();
              //console.log('validateFields:', values);
              onCreate(values);
            })
            .catch((info) => {
              console.log('Validate Failed:', info);
            });
        }}
      >

        <Form
          form={form}
          layout="vertical"
          name="form_in_modal"
          initialValues={{
            modifier: 'public',
          }}
        >
          <Row gutter={[16, 24]}> {/* 添加一个Row组件，并设置列之间的间距 */}
            <Col span={12}> {/* 每个表单项将占据行的1/3（总共24列） */}
              <Form.Item
                name="vehicle"
                label="车辆号"
                rules={[
                  {
                    required: true,
                    message: '请输入车辆号!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="project"
                label="项目名称"
                rules={[
                  {
                    required: true,
                    message: '请输入项目名称!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={[16, 24]}> {/* 添加一个Row组件，并设置列之间的间距 */}
            <Col span={12}> {/* 每个表单项将占据行的1/3（总共24列） */}

              <Form.Item
                name="ecnumber"
                label="边缘计算器编号"
                rules={[
                  {
                    required: true,
                    message: '请输入边缘计算器编号!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}> {/* 每个表单项将占据行的1/3（总共24列） */}

              <Form.Item
                name="remarks"
                label="备注"
                placeholder="请填写项目备注"
                rules={[
                  {
                    required: true,
                    message: '请输入项目备注!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="inputpath"
            label="数据路径"
            placeholder="请填写路径"
            rules={[
              {
                required: true,
                message: '请输入路径!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="savepath"
            label="保存路径"
            placeholder="请填写路径"
            rules={[
              {
                required: true,
                message: '请输入路径!',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Row gutter={[16, 24]}> {/* 添加一个Row组件，并设置列之间的间距 */}
            <Col span={6}> {/* 每个表单项将占据行的1/3（总共24列） */}

              <Form.Item
                name="chantitle_spd"
                label="速度"
                placeholder="请填写速度"
                rules={[
                  {
                    required: true,
                    message: '请输入速度名称!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={6}> {/* 每个表单项将占据行的1/3（总共24列） */}

              <Form.Item
                name="chantitle_throttle"
                label="油门"
                placeholder="请填写油门"
                rules={[
                  {
                    required: true,
                    message: '请输入油门名称!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={6}> {/* 每个表单项将占据行的1/3（总共24列） */}

              <Form.Item
                name="chantitle_brake"
                label="制动"
                placeholder="请填写制动"
                rules={[
                  {
                    required: true,
                    message: '请输入制动名称!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={6}> {/* 每个表单项将占据行的1/3（总共24列） */}

              <Form.Item
                name="chantitle_steering"
                label="转向"
                placeholder="请填写转向"
                rules={[
                  {
                    required: true,
                    message: '请输入转向名称!',
                  },
                ]}
              >
                <Input />
              </Form.Item>

            </Col>

          </Row>

          <Row gutter={[16, 24]}> {/* 添加一个Row组件，并设置列之间的间距 */}
            <Col span={8}> {/* 每个表单项将占据行的1/3（总共24列） */}

              <Form.Item
                name="chantitle_engspd"
                label="引擎转速"
                placeholder="请填写引擎转速"
                rules={[
                  {
                    required: true,
                    message: '请输入引擎转速名称!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={8}> {/* 每个表单项将占据行的1/3（总共24列） */}

              <Form.Item
                name="chantitle_accybody"
                label="Y加速度"
                placeholder="请填写车身Y加速度"
                rules={[
                  {
                    required: true,
                    message: '请输入车身Y加速度名称!',
                  },
                ]}
              >
                <Input />
              </Form.Item>

            </Col>
            <Col span={8}> {/* 每个表单项将占据行的1/3（总共24列） */}

              <Form.Item
                name="brakezerostandard"
                label="制动零位"
                placeholder="请填写制动零位"
                rules={[
                  {
                    required: true,
                    message: '请输入制动零位名称!',
                  },
                ]}
              >
                <InputNumber />
              </Form.Item>
            </Col>

          </Row>

          <Row gutter={[16, 24]}> {/* 添加一个Row组件，并设置列之间的间距 */}
            <Col span={8}> {/* 每个表单项将占据行的1/3（总共24列） */}

              <Form.Item
                name="importgps"
                label="GPS导入否"
                placeholder="请选择是否导入"

              >
                <Switch checkedChildren="开启" unCheckedChildren="关闭" onChange={(e) => {

                }} />
              </Form.Item>
            </Col>
            <Col span={8}> {/* 每个表单项将占据行的1/3（总共24列） */}

              <Form.Item
                name="importspd"
                label="速度导入否"
                placeholder="请选择是否导入"

              >
                <Switch checkedChildren="开启" unCheckedChildren="关闭" onChange={(e) => {

                }} />
              </Form.Item>

            </Col>
            <Col span={8}> {/* 每个表单项将占据行的1/3（总共24列） */}

              <Form.Item
                name="importsteering"
                label="转角导入否"
                placeholder="请选择是否导入"

              >
                <Switch checkedChildren="开启" unCheckedChildren="关闭" onChange={(e) => {

                }} />
              </Form.Item>
            </Col>

          </Row>

          <Row gutter={[16, 24]}> {/* 添加一个Row组件，并设置列之间的间距 */}
            <Col span={8}> {/* 每个表单项将占据行的1/3（总共24列） */}

              <Form.Item
                name="importengrpm"
                label="ENGRPM导入否"
                placeholder="请选择是否导入"

              >
                <Switch checkedChildren="开启" unCheckedChildren="关闭" onChange={(e) => {

                }} />
              </Form.Item>
            </Col>
            <Col span={8}> {/* 每个表单项将占据行的1/3（总共24列） */}

              <Form.Item
                name="importspdfromto"
                label="Fromto导入否"
                placeholder="请选择是否导入"

              >
                <Switch checkedChildren="开启" unCheckedChildren="关闭" onChange={(e) => {

                }} />
              </Form.Item>

            </Col>
            <Col span={8}> {/* 每个表单项将占据行的1/3（总共24列） */}

              <Form.Item
                name="importstatistic"
                label="统计导入否"
                placeholder="请选择是否导入"

              >
                <Switch checkedChildren="开启" unCheckedChildren="关闭" onChange={(e) => {
                  //form.setFieldsValue(e ? 1 : 0);
                }} />
              </Form.Item>
            </Col>

          </Row>
        </Form>

        {/* <Form
          form={form}
          layout="vertical"
          name="form_in_modal"
          initialValues={{
            modifier: 'public',
          }}
        >

          <Form.Item
            name="vehicle"
            label="车号"
            placeholder="请填写车号"
            rules={[
              {
                required: true,
                message: '请输入车号!',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="project"
            label="项目"
            placeholder="请填写项目"
            rules={[
              {
                required: true,
                message: '请输入项目!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="ecnumber"
            label="边缘计算器"
            placeholder="请填写边缘计算器"
            rules={[
              {
                required: true,
                message: '请输入边缘计算器!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="remarks"
            label="备注"
            placeholder="请填写项目备注"
            rules={[
              {
                required: true,
                message: '请输入项目备注!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="inputpath"
            label="数据路径"
            placeholder="请填写路径"
            rules={[
              {
                required: true,
                message: '请输入路径!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="savepath"
            label="保存路径"
            placeholder="请填写路径"
            rules={[
              {
                required: true,
                message: '请输入路径!',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="chantitle_spd"
            label="速度"
            placeholder="请填写速度"
            rules={[
              {
                required: true,
                message: '请输入速度名称!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="chantitle_throttle"
            label="油门"
            placeholder="请填写油门"
            rules={[
              {
                required: true,
                message: '请输入油门名称!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="chantitle_brake"
            label="制动"
            placeholder="请填写制动"
            rules={[
              {
                required: true,
                message: '请输入制动名称!',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="chantitle_steering"
            label="转向"
            placeholder="请填写转向"
            rules={[
              {
                required: true,
                message: '请输入转向名称!',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="chantitle_engspd"
            label="引擎转速"
            placeholder="请填写引擎转速"
            rules={[
              {
                required: true,
                message: '请输入引擎转速名称!',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="chantitle_accybody"
            label="Y加速度"
            placeholder="请填写车身Y加速度"
            rules={[
              {
                required: true,
                message: '请输入车身Y加速度名称!',
              },
            ]}
          >
            <Input />
          </Form.Item>


          <Form.Item
            name="brakezerostandard"
            label="制动零位"
            placeholder="请填写制动零位"
            rules={[
              {
                required: true,
                message: '请输入制动零位名称!',
              },
            ]}
          >
            <InputNumber />
          </Form.Item>

          <Form.Item
            name="importgps"
            label="GPS导入否"
            placeholder="请选择是否导入"

          >
            <Switch checkedChildren="开启" unCheckedChildren="关闭" onChange={(e) => {

            }} />
          </Form.Item>


          <Form.Item
            name="importspd"
            label="速度导入否"
            placeholder="请选择是否导入"

          >
            <Switch checkedChildren="开启" unCheckedChildren="关闭" onChange={(e) => {

            }} />
          </Form.Item>

          <Form.Item
            name="importsteering"
            label="转角导入否"
            placeholder="请选择是否导入"

          >
            <Switch checkedChildren="开启" unCheckedChildren="关闭" onChange={(e) => {

            }} />
          </Form.Item>

          <Form.Item
            name="importengrpm"
            label="ENGRPM导入否"
            placeholder="请选择是否导入"

          >
            <Switch checkedChildren="开启" unCheckedChildren="关闭" onChange={(e) => {

            }} />
          </Form.Item>

          <Form.Item
            name="importspdfromto"
            label="Fromto导入否"
            placeholder="请选择是否导入"

          >
            <Switch checkedChildren="开启" unCheckedChildren="关闭" onChange={(e) => {

            }} />
          </Form.Item>

          <Form.Item
            name="importstatistic"
            label="统计导入否"
            placeholder="请选择是否导入"

          >
            <Switch checkedChildren="开启" unCheckedChildren="关闭" onChange={(e) => {
              //form.setFieldsValue(e ? 1 : 0);
            }} />
          </Form.Item>
        </Form> */}
      </Modal>
    );
  };

  //这个方法页面加载时就会不停的执行
  const EditableCell = ({ editing, dataIndex, title, inputType, record, index, children, ...restProps }) => { // 定义 EditableCell 组件并传入 props

    return (
      <td {...restProps}>
        {editing ? ( // 如果正在编辑，渲染带有相应 props 的 inputNode
          <Form.Item
            name={dataIndex}
            style={{ margin: 0 }}
            rules={[
              {
                required: true,
                message: `请输入${title}!`,
              },
            ]}
          >
            {dataIndex === "importgps" || dataIndex === "importspd" || dataIndex === "importstatistic" || dataIndex === "importsteering" || dataIndex === "importengrpm" || dataIndex === "importspdfromto" ? <InputNumber max={1} min={0} /> : dataIndex === "brakezerostandard" || dataIndex === "timezone" ? <InputNumber /> : <Input />}
          </Form.Item>
        ) : (
          children // 否则渲染 children（文本）
        )}
      </td>
    );
  };
  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      editable: false,

      width: '1%',
      //render: (name) => `${name.first} ${name.last}`,
    },
    {
      title: '项目',
      dataIndex: 'project',
      editable: true,

    },
    {
      title: '车号',
      dataIndex: 'vehicle',
      editable: true,

    },
    {
      title: '边缘计算器',
      dataIndex: 'ecnumber',
      editable: true,

    },
    {
      title: '备注',
      dataIndex: 'remarks',
      editable: true,

    },
    {
      title: '数据路径',
      dataIndex: 'inputpath',
      editable: true,

    },
    {
      title: '保存路径',
      dataIndex: 'savepath',
      editable: true,

    },
    {
      title: '车速',
      dataIndex: 'chantitle_spd',
      editable: true,

    },
    {
      title: '油门',
      dataIndex: 'chantitle_throttle',
      editable: true,

    },
    {
      title: '制动',
      dataIndex: 'chantitle_brake',
      editable: true,

    },
    {
      title: '转向',
      dataIndex: 'chantitle_steering',
      editable: true,

    },
    {
      title: 'ENGRPM',
      dataIndex: 'chantitle_engspd',
      editable: true,

    },

    // {
    //   title: 'ACCX',
    //   dataIndex: 'chantitle_accxbody',
    //   editable: true,

    // },
    {
      title: '车身Y',
      dataIndex: 'chantitle_accybody',
      editable: true,

    },
    {
      title: '制动零位',
      dataIndex: 'brakezerostandard',
      editable: true,

    },

    {
      title: 'GPS导入否',
      dataIndex: 'importgps',
      editable: true,
      render: (text) => text === 1 ? <Badge status="success" text="是" /> : <Badge status="error " text="否" />,
    },

    {
      title: '车速导入否',
      dataIndex: 'importspd',
      editable: true,
      render: (text) => text === 1 ? <Badge status="success" text="是" /> : <Badge status="error " text="否" />,
    },
    {
      title: '转向导入否',
      dataIndex: 'importsteering',
      editable: true,
      render: (text) => text === 1 ? <Badge status="success" text="是" /> : <Badge status="error " text="否" />,
    },
    {
      title: 'ENGRPM导入否',
      dataIndex: 'importengrpm',
      editable: true,
      render: (text) => text === 1 ? <Badge status="success" text="是" /> : <Badge status="error " text="否" />,
    },
    {
      title: 'Fromto导入否',
      dataIndex: 'importspdfromto',
      editable: true,
      render: (text) => text === 1 ? <Badge status="success" text="是" /> : <Badge status="error " text="否" />,
    },
    {
      title: '统计导入否',
      dataIndex: 'importstatistic',
      editable: true,
      render: (text) => text === 1 ? <Badge status="success" text="是" /> : <Badge status="error " text="否" />,
    },
    {
      //表格最后的操作按钮
      title: '操作',
      dataIndex: 'action',
      width: '3%',
      fixed: 'right',
      render: (_, record) => { // 使用 Popconfirm 组件渲染操作列
        const editable = isEditing(record);//判断这一行的key是否为editingKey，如果是则说明点击了edit，如果不是则说明没有点击

        return editable ? (

          <span>
            <Typography.Link onClick={() => save(record.key)} style={{ marginRight: 8 }}>
              保存
            </Typography.Link>
            <Popconfirm title="确定取消吗?" onConfirm={cancel}>
              <a>取消</a>
            </Popconfirm>
          </span>

        ) : (
          //点击了edit就把这一行的key设为editingKey，重新渲染，然后editable变为true，显示保存和取消a标签，editingKey不等于空说明有行点了edit，则其他行都是disabled
          <Space size="middle">
            <Typography.Link disabled={editingKey !== '' || loginstate.role.loginname === "admin"} onClick={() => edit(record)}>
              编辑
            </Typography.Link>

            <Popconfirm title="确定删除吗?" onConfirm={() => deldata(record.key)} onCancel={cancel} okText="Yes" cancelText="No">
              <a disabled={loginstate.role.loginname === "admin"}>
                删除
              </a>
            </Popconfirm>
          </Space>
        );

      },
    },
  ];
  //添加表单的添加方法
  const onAddDate = async (values) => {

    setOpen(false);
    values.loginname = loginstate.role.loginname;
    // values.importbrake = values.importbrake === true ? 1 : 0;
    values.importengrpm = values.importengrpm === true ? 1 : 0;
    values.importgps = values.importgps === true ? 1 : 0;
    values.importspd = values.importspd === true ? 1 : 0;
    values.importstatistic = values.importstatistic === true ? 1 : 0;
    values.importsteering = values.importsteering === true ? 1 : 0;
    // values.importthrottle = values.importthrottle === true ? 1 : 0;
    values.importspdfromto = values.importspdfromto === true ? 1 : 0;
    //console.log('Received values of form: ', values);
    const r = await addtrigger(values);
    if (r.error.originalStatus === 200) {
      //console.log("成功")
      messagesucess(r.error.data);

    } else {
      messageerror(r.error.data);
    }

  };
  const save = async (key) => {
    //这里的row就是表单的所有项的值作为一个row对象存储
    //这里会异步
    const row = await form.validateFields();

    row.key = key;
    row.loginname = loginstate.role.loginname;

    //发送put请求到服务器
    const r = await edittrigger(row);
    //console.log(r);
    if (r.error.originalStatus === 200) {
      //console.log("成功")
      messagesucess(r.error.data);

    } else {
      messageerror(r.error.data);
    }
    setEditingKey('');
    setSelectedRowKeys([]); // 清除表格选择
    setparaisselected(false);//保存时让button不起作用
  };

  const cancel = () => { // 定义 cancel 函数以重置 editingKey state
    setEditingKey('');

  };
  const deldata = async (key) => { // 定义 cancel 函数以重置 editingKey state
    //console.log(key);
    const r = await deltrigger(key);
    if (r.error.originalStatus === 200) {
      //console.log("成功")
      messagesucess(r.error.data);

    } else {
      messageerror(r.error.data);
    }
    setEditingKey('');

  };
  const handleTableChange = (pagination, filters, sorter) => {

    setTableParams({
      pagination,
      //filters,
      // ...sorter,
    });

    // pagination分页异常值如果和tableParams里的分页异常值不一样，就把异常值清零，重新发送请求
    // if (pagination.pageSize !== tableParams.pagination?.pageSize) {
    //   setData([]);
    // }
  };
  //这个比EditableCell先执行，这个是点了edit后展示的form表单的设置
  const mergedColumns = columns.map((col) => { // 通过映射 columns 数组定义 mergedColumns 数组
    if (!col.editable) { // 如果列不可编辑，返回列
      return col;
    }

    return {
      ...col, // 否则返回编辑行新对象，其 render 函数为 EditableCell 组件
      onCell: (record) => (

        {

          record,
          //inputType: col.dataIndex === 'category' ? 'radio' : 'text',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: isEditing(record),//判断这一行的key是否为editingKey，为true说明这一行点击了edit
          // 将单元格的原始值传递给 EditableCell 组件

        }),
    };
  });

  //一旦tableParams发生改变，就调用此方法，当然第一次加载页面的时候也会调用此方法，所以第一次总是会去发送请求
  //useEffect 钩子函数将在组件渲染后执行 
  useEffect(() => {
    //如果请求成功则调用setTableParams方法

    if (result.isSuccess) {
      //console.log(result.data.pagedata);
      setTableParams({
        ...tableParams,
        pagination: {
          ...tableParams.pagination,
          total: result.data.total,

        },
      });
    }

  }, [result.isSuccess]);

  // useEffect(() => {
  //   console.log(badgestatus);

  // }, [badgestatus]);


  return (
    <>
      {/* 必须把contextHolder包裹整个组件才能显示message消息框 */}
      {contextHolder}
      <Button
        onClick={() => {
          setOpen(true);
        }}
        type="primary"
        disabled={loginstate.role.loginname === "admin"}
        //如果是admin登陆的就不需要执行添加特定用户参数
        //disabled={loginstate.role.loginname === "admin"}
        style={{
          marginBottom: 16,
        }}
      // disabled={loginstate.role==="admin"?false:true}
      >
        添加
      </Button>
      <CollectionCreateForm
        open={open}
        onCreate={onAddDate}

        onCancel={() => {
          setOpen(false);
        }}
      />
      <Form form={form} component={false}>

        <Table
          components={{
            body: {
              cell: EditableCell, // 使用 EditableCell 组件作为表格单元格
            },
          }}
          bordered
          rowHeight={100}
          rowSelection={rowSelection}
          dataSource={result.isSuccess ? result.data.pagedata : []} // 将 dataSource prop 设置为异常值 state
          columns={mergedColumns} // 将 columns prop 设置为 mergedColumns 数组
          rowClassName="editable-row"
          pagination={tableParams.pagination}
          loading={result.isLoading}
          onChange={handleTableChange}
          scroll={{ x: 'max-content' }}
        />
        <Form.Item name="range-picker" label="选择日期范围">
          <DatePicker.RangePicker
            status="error"
            style={{
              width: '100%',
            }}
            onChange={dateselect}
          />
        </Form.Item>

        <Form.Item>
          <Button
            block type="primary"
            size="large"
            loading={loading}
            disabled={!paraisselected || loginstate.role.loginname === "admin" || !dateselected}
            onClick={dataimportexcute}
          >执行计算</Button>
        </Form.Item>
        {/* <Form.Item>
          <Button
            block type="primary"
            size="large"
            loading={loading}
            danger
            disabled={!paraisselected || loginstate.role.loginname === "admin"|| !dateselected}
            onClick={dataimportexcute}
          >取消导入</Button>
        </Form.Item> */}
      </Form>
      {excutesuccess === 1 ? <Alert
        message="已发送请求"
        description={<div dangerouslySetInnerHTML={{ __html: resultString }} />}
        type="success"
        showIcon

      /> : excutesuccess === 0 ? <Alert
        message="发送请求失败"
        description="半小时计算保存CSV失败，请查看日志"
        type="Error"
        showIcon

      /> : <></>

      }

    </>
  )
}

export default UserHalfHourCalProp